<template>
  <div class="app-container">
    <el-form
      :model="queryParams"
      ref="queryForm"
      :inline="true"
      v-show="showSearch"
      label-width="68px"
    >
      <!-- <el-form-item label="入库时间" prop="inTime">
        <el-date-picker
          clearable
          size="small"
          v-model="queryParams.inTime"
          type="datetime"
          value-format="yyyy-MM-dd HH:mm:ss"
          placeholder="选择入库时间"
        >
        </el-date-picker>
      </el-form-item> -->
      <!-- <el-form-item label="部门" prop="deptId">
         <el-cascader
            v-model="queryParams.deptId"
            :options="deptOptions"
            :show-all-levels="false"
            :props="defaultProps"
          ></el-cascader>
      </el-form-item> -->
      <!-- <el-form-item label="入库人" prop="inOutUser">
        <el-input
          v-model="queryParams.inOutUser"
          placeholder="请输入入库人"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item> -->
      <el-form-item label="物资名称" prop="materialName">
        <el-input
          v-model="queryParams.materialName"
          placeholder="请输入物资名称"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="仓库名称" prop="houseId">
        <el-select clearable v-model="queryParams.houseId" placeholder="请选择仓库">
          <el-option v-for="item in houseList" :key="item.id" :label="item.warehouse" :value="item.id">
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button
          type="primary"
          icon="el-icon-search"
          size="mini"
          @click="handleQuery"
          >搜索</el-button
        >
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery"
          >重置</el-button
        >
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['park:maMaterial:add']"
          >新增</el-button
        >
      </el-col>
      <!--<el-col :span="1.5">-->
        <!--<el-button-->
          <!--type="success"-->
          <!--plain-->
          <!--icon="el-icon-edit"-->
          <!--size="mini"-->
          <!--:disabled="single"-->
          <!--@click="handleUpdate"-->
          <!--v-hasPermi="['park:maMaterial:edit']"-->
          <!--&gt;修改</el-button-->
        <!--&gt;-->
      <!--</el-col>-->
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['park:maMaterial:remove']"
          >删除</el-button
        >
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-upload"
          size="mini"
          @click="handleImport"
          v-hasPermi="['park:maMaterial:edit']"
        >导入</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['park:maMaterial:export']"
          >导出</el-button>
      </el-col>
      <right-toolbar
        :showSearch.sync="showSearch"
        @queryTable="getList"
      ></right-toolbar>
    </el-row>

    <el-table
      v-loading="loading"
      :data="maMaterialList"
      @selection-change="handleSelectionChange"
    >
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column
        label="物资名称"
        align="center"
        prop="materialName"
        width="180"
      >
      </el-table-column>
      <el-table-column label="规格型号" align="center" prop="standards" />
      <el-table-column label="物料编码" align="center" prop="materialNum" />

      <el-table-column label="单位" align="center" prop="unitName" />
      <el-table-column label="数量" align="center" prop="quantity">
        <template slot-scope="scope">
          <span>{{scope.row.quantity==null?'0':scope.row.quantity}}</span>
        </template>
      </el-table-column>
      <el-table-column label="类别" align="center" prop="categoryName" />
      <el-table-column label="仓库名称" align="center" prop="warehouse" />
      <el-table-column label="仓库编号" align="center" prop="houseNum" />
      <el-table-column label="单价（元）" align="center" prop="unitPrice" />
      <el-table-column label="总价（元）" align="center" prop="totalPrice" />
      <el-table-column label="用途" align="center" prop="purpose" />
      <el-table-column label="备注" align="center" prop="remark" />
      <el-table-column
        label="操作"
        align="center"
        class-name="small-padding fixed-width"
      >
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-view"
            @click="handleShow(scope.row)"
            v-hasPermi="['park:maInOutRecord:show']"
            >查看</el-button
          >
<!--          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['park:maMaterial:edit']"
            >修改</el-button
          >-->
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['park:maMaterial:remove']"
            >删除</el-button
          >
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total > 0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 抄表导入对话框 -->
    <el-dialog :title="upload.title" :visible.sync="upload.open" width="400px" append-to-body>
      <el-upload
        ref="upload"
        :limit="1"
        accept=".xlsx, .xls"
        :headers="upload.headers"
        :action="upload.url + '?updateSupport=' + upload.updateSupport"
        :disabled="upload.isUploading"
        :on-progress="handleFileUploadProgress"
        :on-success="handleFileSuccess"
        :auto-upload="false"
        drag
      >
        <i class="el-icon-upload"></i>
        <div class="el-upload__text">
          将文件拖到此处，或
          <em>点击上传</em>
        </div>
        <div class="el-upload__tip" slot="tip">
          <!--<el-checkbox v-model="upload.updateSupport" />是否更新已经存在的数据-->
          <el-link type="info" style="font-size:12px" @click="importTemplate">下载模板</el-link>
        </div>
        <div class="el-upload__tip" style="color:red" slot="tip">提示：仅允许导入“xls”或“xlsx”格式文件！</div>
      </el-upload>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitFileForm">确 定</el-button>
        <el-button @click="upload.open = false">取 消</el-button>
      </div>
    </el-dialog>

    <!-- 添加或修改物资管理对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
      <el-form
        :disabled="showOpen"
        ref="form"
        :model="form"
        :rules="rules"
        label-width="80px"
      >
        <el-form-item label="物资名称" prop="materialName">
          <el-input v-model="form.materialName" placeholder="请输入物资名称" />
        </el-form-item>
        <el-form-item label="规格型号" prop="standards">
          <el-input v-model="form.standards" placeholder="请输入规格型号" />
        </el-form-item>
        <!--<el-form-item label="编码规格" prop="sysBmId">-->
          <!--<treeselect v-model="form.sysBmId" :options="sysBmTypeList" :normalizer="normalizer" placeholder="请选择编码规格" @select="treeSelectFn"/>-->
        <!--</el-form-item>-->
        <el-form-item label="类别" prop="category">
          <!--<el-input v-model="form.category" placeholder="请输入类别" />-->
          <!--<el-cascader v-model="form.category" :disabled="false" :options="sysBmTypeList" :props="propsBm" :show-all-levels="false" @change="treeSelectFn"></el-cascader>-->
          <el-cascader disabled v-model="form.category" filterable :options="sysBmTypeList" :props="propsBm" :show-all-levels="false" @change="treeSelectFn"></el-cascader>
        </el-form-item>
        <el-form-item label="物料编码" prop="materialNum">
          <el-input disabled v-model="form.materialNum" placeholder="请输入物料编码" />
        </el-form-item>
        <el-form-item label="单位" prop="unit">
          <el-select v-model="form.unit" placeholder="请选择单位">
            <el-option
              v-for="item in unitTypeList"
              :key="item.dictValue"
              :label="item.dictLabel"
              :value="item.dictValue"
            >
            </el-option>
          </el-select>
        </el-form-item>
        <!--<el-form-item label="物资类别" prop="category">-->
          <!--<el-select v-model="form.category" placeholder="请选择物资类别">-->
            <!--<el-option-->
              <!--v-for="item in materialCategoryList"-->
              <!--:key="item.dictValue"-->
              <!--:label="item.dictLabel"-->
              <!--:value="item.dictValue"-->
            <!--&gt;-->
            <!--</el-option>-->
          <!--</el-select>-->
        <!--</el-form-item>-->
        <el-form-item label="数量" prop="quantity">
          <el-input disabled v-model.number="form.quantity" type="number" placeholder="请输入数量" />
        </el-form-item>
        <el-form-item label="单价" prop="unitPrice">
          <el-input v-model.number="form.unitPrice" type="number" placeholder="请输入单价" />
        </el-form-item>
        <el-form-item label="用途" prop="purpose">
          <el-input v-model="form.purpose" placeholder="请输入用途" />
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input
            v-model="form.remark"
            type="textarea"
            placeholder="请输入内容"
          />
        </el-form-item>
      </el-form>

      <el-table v-if="showOpen" :data="form.houseQuantityList">
        <el-table-column label="仓库" align="center" prop="warehouse" />
        <el-table-column label="数量" align="center" prop="quantity" />
      </el-table>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm"
          >确 定{{ totalPrice }}</el-button
        >
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {
  listmaMaterialV2,
  getmaMaterial,
  delmaMaterial,
  delHouseMaMaterial,
  addmaMaterial,
  updatemaMaterial,
} from "@/api/smartParks/property/propertySupplies";
import { listSysBmGoods } from"@/api/system/sysBmGoods.js"
import { treeselect } from "@/api/system/dept";
import { listData } from "@/api/system/dict/data";
import { getToken } from "@/utils/auth";
import { listMaWarehouse } from "@/api/smartParks/park/maWarehouse";
import * as request from '@/utils/request';

export default {
  name: "maMaterial",
  components: {},
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 物资管理表格数据
      maMaterialList: [],
      houseList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        inTime: null,
        deptId: null,
        inUser: null,
        material: null,
        standards: null,
        unit: null,
        amount: null,
        unitPrice: null,
        totalPrice: null,
        usage: null,
      },
      deptOptions: [],
      defaultProps: {
        emitPath: false,
        children: "children",
        label: "label",
        value: "id",
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        materialName: [{ required: true, message: "物资名称不能为空", trigger: "blur" }],
        standards: [{ required: true, message: "规格型号不能为空", trigger: "blur" }],
        sysBmId: [{ required: true, message: "请选择编码规格", trigger: "change" }]
      },
      // 用户导入参数
      upload: {
        // 是否显示弹出层
        open: false,
        // 弹出层标题
        title: "",
        // 是否禁用上传
        isUploading: false,
        // 是否更新已经存在的用户数据
        updateSupport: 0,
        // 设置上传的请求头部
        headers: { Authorization: getToken() },
        // 上传的地址
        url: process.env.VUE_APP_BASE_API + "/park/maMaterial/importData"
      },
      // 物资类型列表
      //materialCategoryList: [],
      unitTypeList:[],
      sysBmTypeList:[],
      showOpen: false,
    };
  },
  computed: {
    totalPrice: {
      get: function () {
        this.totalPrice = this.form.amount * this.form.unitPrice;
        // return this.form.amount * this.form.unitPrice;
      },
      set: function (newValue) {
        this.$set(this.form, "totalPrice", newValue);
      },
    },
  },

  created() {
    this.getList();
    this.getTreeselect();
    this.getbmTree();
    this.getHouseList();
  },
  methods: {
    getHouseList(){
      listMaWarehouse().then((response) => {
        this.houseList = response.rows;
      })
    },
    /** 导入按钮操作 */
    handleImport() {
      this.upload.title = "库存导入";
      this.upload.open = true;
    },
    // 文件上传中处理
    handleFileUploadProgress(event, file, fileList) {
      this.upload.isUploading = true;
    },
    // 文件上传成功处理
    handleFileSuccess(response, file, fileList) {
      this.upload.open = false;
      this.upload.isUploading = false;
      this.$refs.upload.clearFiles();
      this.$alert(response.msg, "导入结果", { dangerouslyUseHTMLString: true });
      this.getList();
    },
    // 提交上传文件
    submitFileForm() {
      this.$refs.upload.submit();
    },
    /** 下载模板操作 */
    importTemplate() {
      this.download('park/maMaterial/importTemplate',{
        ...this.queryParams
      }, `物料导入.xlsx`)
    },
    /** 查询部门下拉树结构 */
    getTreeselect() {
      treeselect().then((response) => {
        this.deptOptions = response.data;
      });
    },
    /** 查询物资类型列表 */
    getdictDataList() {
      // listData({ dictType: "material_category" }).then((response) => {
      //   this.materialCategoryList = response.rows;
      // });
      listData({ dictType: "unit_type" }).then((response) => {
        this.unitTypeList = response.rows;
      });
    },
    /** 查询物资管理列表 */
    getList() {
      this.loading = true;
      this.getdictDataList();
      listmaMaterialV2(this.queryParams).then((response) => {
        response.rows.forEach((item) => {
          // this.materialCategoryList.forEach((itemType) => {
          //   if (itemType.dictValue == item.category) {
          //     item.categoryName = itemType.dictLabel;
          //   }
          // });

          this.unitTypeList.forEach((itemType) => {
            if (itemType.dictValue == item.unit) {
              item.unitName = itemType.dictLabel;
            }
          });
        });
        this.maMaterialList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        inTime: null,
        deptId: null,
        inUser: null,
        material: null,
        standards: null,
        materialNum:null,
        unit: null,
        amount: null,
        unitPrice: null,
        quantity:null,
        totalPrice: null,
        usage: null,
        createBy: null,
        createTime: null,
        updateBy: null,
        updateTime: null,
        remark: null,
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map((item) => item.id);
      this.single = selection.length !== 1;
      this.multiple = !selection.length;
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.showOpen = false;
      this.title = "添加物资管理";
    },
    handleShow(row) {
      const id = row.materialId || this.ids;
        this.form = row;
        this.open = true;
        this.showOpen = true;
        this.title = "物资详情";
      getmaMaterial(id).then((response) => {
      });
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.showOpen = false;
      this.reset();
      this.open = true;
      this.form = row;
      this.title = "修改物资管理";
      return
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate((valid) => {
        if (valid) {
          if (this.form.id != null) {
            updatemaMaterial(this.form).then((response) => {
              this.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addmaMaterial(this.form).then((response) => {
              this.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      if (row.quantity > 0) {
        this.msgError("当前物资数量大于0，不能删除");
      } else {
        this.$confirm(
          '是否确认删除物资管理编号为"' + ids + '"的数据项?',
          "警告",
          {
            confirmButtonText: "确定",
            cancelButtonText: "取消",
            type: "warning",
          }
        ).then(function () {
            return delHouseMaMaterial(ids);
        }).then(() => {
            this.getList();
            this.msgSuccess("删除成功");
        });
      }
    },
    /** 导出按钮操作 */
    handleExport() {
      // this.download(
      //   "park/maMaterial/export",
      //   {
      //     ...this.queryParams,
      //   },
      //   `park_maMaterial.xlsx`
      // );
      request.downloadCheckMeter1('park/maMaterial/exportStock', {
        ...this.queryParams
      }, `物资库存.xlsx`)
    },
    /** 转换编码配置数据结构 */
    normalizer(node) {
      if (node.children && !node.children.length) {
        delete node.children;
      }
      return {
        id: node.bmId,
        label: node.name,
        children: node.children
      };
    },
    /** 查询编码配置下拉树结构 */
    getbmTree() {
      listSysBmGoods().then(response => {
        this.sysBmTypeList = [];
        const data = { bmId: 0, name: '请选择', children: [] };
        data.children = this.handleTree(response.data, "bmId", "parentId");
        this.sysBmTypeList.push(data);
      });
    },
    treeSelectFn(node){
      return
      if (node.bmId==0){
        this.form.lv=1
        this.form.parentId=0
      }else {
        this.form.parentId=node.bmId
        this.form.lv=node.lv+1
      }
    },
  },
};
</script>
